package com.zxy.service;


import cn.echo.exception.BizException;
import cn.echo.threadlocal.LocalUserUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.zxy.dao.PoItemDao;
import com.zxy.dao.PoMasterDao;
import com.zxy.enums.PoMasterStatus;
import com.zxy.model.PoItem;
import com.zxy.model.PoItemQuery;
import com.zxy.model.PoMaster;
import com.zxy.model.PoMasterQuery;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class PoService {
    @Value("${totalPrices}")
    private BigDecimal totalPrices;

    @Autowired
    private PoMasterDao poMasterDao;
    @Autowired
    private PoItemDao poItemDao;

    public List<PoMaster> select(PoMasterQuery query) {

        return poMasterDao.select(query);
    }

//    @Transactional
//    事务执行原理：通过aop技术，在目标方法执行之前，把事务打开，然后执行目标方法
//    当目标方法执行正常的时候，提交事务，如果有报异常，就执行事务回滚
    public int insert(PoMaster poMaster) {
//首先做判断
//"PO" 代表采购单 yyyyMMddHHmmssSSS HH24小时  SSS 毫秒
        String poMasterId = "PO" + DateUtil.format(DateUtil.date(),"yyyyMMddHHmmssSSS");
        poMaster.setId(poMasterId);
        poMaster.setPurchaser(LocalUserUtils.get().getNickName());
        poMaster.setStatus(PoMasterStatus.NEW.getCode());
//        校验总价 保证数据的安全性
        BigDecimal totalPrice = BigDecimal.ZERO;
        List<PoItem> items = poMaster.getItems();
        for (PoItem item : items) {
            item.setPoId(poMasterId);
            item.setLastUpdateBy(LocalUserUtils.get().getNickName());
             totalPrice = NumberUtil.add(totalPrice, NumberUtil.mul(item.getPrice(), item.getQty()));
        }
        if (poMaster.getTotalPrice().doubleValue() != totalPrice.doubleValue()){
            throw new BizException(701,"采购总价异常");
        }
        if (totalPrice.doubleValue()<totalPrices.doubleValue()){
            poMaster.setStatus(PoMasterStatus.APPROVE.getCode());
        }else {
            MailAccount account = new MailAccount();
            account.setHost("smtp.163.com");//网易
            account.setPort(25);
            account.setAuth(true);
            account.setFrom("zxy06291@163.com");
            account.setUser("zxy06291");
            account.setPass("SUZXYSMVMQFRPPXV");
            String subject = StrUtil.format("采购单：[{}] 总金额：{},需要李总您审批。",
                    poMaster.getId(),
                    poMaster.getTotalPrice());

            StringBuilder sb = new StringBuilder();
            sb.append("<table border='1'>");
            sb.append("<tr><td>商品名称</td><td>数量</td><td>单价</td><td>合计</td></tr>");
            for(PoItem item : items){
                sb.append("<tr>");
                sb.append(StrUtil.format("<td>{}</td>",item.getProductName()));
                sb.append(StrUtil.format("<td>{}</td>",item.getQty()));
                sb.append(StrUtil.format("<td>{}</td>",item.getPrice()));
                sb.append(StrUtil.format("<td>{}</td>",NumberUtil.mul(item.getPrice(),item.getQty())));
                sb.append("</tr>");
            }
            sb.append("</table>");
//            MailUtil.send(account, CollUtil.newArrayList("2913929510@qq.com","wzk0903@vip.qq.com","zxy06291@163.com","1803172431@qq.com"), subject,
//                    sb.toString(), true);
//            https://oapi.dingtalk.com/robot/send?access_token=567b20b4407d3f75c20e1cb51c1f84b392617ee4045c4fcf1ef3b19d95fe8198
            String url = "https://oapi.dingtalk.com/robot/send?access_token=567b20b4407d3f75c20e1cb51c1f84b392617ee4045c4fcf1ef3b19d95fe8198";

        }

        PoService poService =(PoService) AopContext.currentProxy();
        poService.add(poMaster);
//        add(poMaster);
        return 1;

    }
    @Transactional
    public void add(PoMaster poMaster){
        poMasterDao.insert(poMaster);
        poItemDao.insert(poMaster.getItems());

    }
    public int update(PoMaster poMaster) {
        return poMasterDao.update(poMaster);
    }


    public List<PoItem> selectItem(PoItemQuery query) {
        return poItemDao.select(query);
    }
}
